package com.itzmn.java.javase.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/26 15:33
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description:
 */
public class BIOServer1 {

    private int port;
    private ServerSocket serverSocket = null;

    public BIOServer1(){
        this(8080);
    }

    public BIOServer1(int port){
        this.port = port;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务器启动成功，port:"+this.port);
        } catch (IOException e) {
            System.out.println("服务器启动失败...");
            e.printStackTrace();
        }
    }

    /**
     * 处理客户端连接的业务
     */
    private void listen(){
            while (true){
                InputStream inputStream = null;
                try {
                    System.out.println("阻塞，等待客户端连接..."+System.currentTimeMillis());
                    Socket socket = serverSocket.accept();
                    System.out.println("有客户端连接了...."+System.currentTimeMillis());
                    inputStream = socket.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len = inputStream.read(bytes);
                    System.out.println("客户端说:"+new String(bytes,0,len));
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }
    public static void main(String[] args) {
        new BIOServer1().listen();
    }
}
